<?php 
header("Content-Type:text/html;charset=UTF-8");
error_reporting(3);
date_default_timezone_set('Africa/Lubumbashi');//Africa/Lubumbashi//PRC
class db_connect{
    private $host;
    private $db_name;
    private $user;
    private $pwd;
    private $charset;
    private $con;
    public $tab;
    public $field='*';
    public $where;
    public $group;
    public $order;

    public function __construct($host='localhost',$db_name='',$user='',$pwd='',$charset='utf8'){
        $this->host=$host;
        $this->db_name=$db_name;
        $this->user=$user;
        $this->pwd=$pwd;
        $this->charset=$charset;
        $this->connect();
    }

    public function connect(){
        $this->con=@mysqli_connect($this->host,$this->user,$this->pwd) or die("MySQL连接失败") ;
//        print_r($conn);die;
        mysqli_query($this->con,"set names 'utf8'");
        mysqli_select_db($this->con,$this->db_name);
//        print_r($return);die();
    }

    public function changeDB($db_name=''){
        $this->db_name=$db_name;
        return mysqli_query($this->con,'use '.$this->db_name);
    }

    public function field($field){
        if(empty($field)){
            $this->field=' * ';
        }else{
            $this->field=' '.$field.' ';
        }
        return $this;
    }
    /*1-key,2-value,3-condition*/
    public function where($where){
        $this->where=' where ';
        if(!empty($where)){
            if(is_array($where)){
                $i=0;
                $keys=array_keys($where);
                if($keys===array_keys($keys)){
                    foreach ($where as $k => $v){
                        if($i<=0){
                            $this->where.=' ('.$v[0].' '.$v[2].' '.$v[1].') ';
                        }else{
                            $this->where.=' and ('.$v[0].' '.$v[2].' '.$v[1].') ';
                        }
                        $i++;
                    }
                }else{
                    foreach ($where as $k => $v){
                        if($i<=0){
                            $this->where.=' (`'.$k.'` = \''.$v.'\') ';
                        }else{
                            $this->where.=' and (`'.$k.'` = \''.$v.'\') ';
                        }
                        $i++;
                    }
                }
            }else{
                $this->where.=$where.' ';
            }
        }
        return $this;
    }

    public function group($group){
        if(!empty($group)){
            $this->group=' group by '.$group.' ';
        }
        return $this;
    }

    public function order($order){
        if(!empty($order)){
            $this->order=' order by '.$order.' ';
        }
        return $this;
    }

    public function query($sql='',$type='select'){
        if($type=='select'){
			$res=mysqli_query($this->con,$sql);
			$data=[];
			while ($row=mysqli_fetch_assoc($res)) {
				$data[]=$row;
			}
		}else{
			$data=mysqli_query($this->con,$sql);
		}
        return $data;
    }

    public function M($tab=''){
        if(!empty($tab)){
            $this->tab=$tab;
        }
        return $this;
    }

    public function select(){
        if(empty($this->tab)){die('未指定数据表');}
        $sql='select '.$this->field.' from `'.$this->tab.'` '.$this->where.' '.$this->group.' '.$this->order;
        $res=mysqli_query($this->con,$sql);
        $data=[];
        while ($row=@mysqli_fetch_assoc($res)) {
            $data[]=$row;
        }
		$this->field='*';
		$this->group='';
		$this->order='';
		$this->where='';
		$this->tab='';
        return $data;
    }
	
	public function find(){
		if(empty($this->tab)){die('未指定数据表');}
        $sql='select '.$this->field.' from '.$this->tab.' '.$this->where.' '.$this->group.' '.$this->order.' limit 0,1';
        $res=mysqli_query($this->con,$sql);
        $data=@mysqli_fetch_assoc($res);
		$this->field='*';
		$this->group='';
		$this->order='';
		$this->where='';
		$this->tab='';
        return $data;
	}
	
	public function add($data){
		if(empty($this->tab)){die('未指定数据表');}
		$key=[];
		$val=[];
		foreach($data as $k => $v){
			$key[]='`'.$k.'`';
			$val[]='\''.$v.'\'';
		}
		$sql='INSERT INTO `'.$this->tab.'` ('.implode(',',$key).') VALUES ('.implode(',',$val).');';
		$res=mysqli_query($this->con,$sql);
		return $res;
	}
	
	public function addAll($data){
		if(empty($this->tab)){die('未指定数据表');}
		$val=[];
		$key=[];
		$flag=1;
		if(empty($data)){
			return false;
		}else{
			foreach($data as $k => $v){
				$value=[];
				foreach($v as $ke => $va){
					if($flag==1){
						$key[]='`'.$ke.'`';
					}
					$value[]=$va;
				}
				$val[]='('.implode(',',$value).')';
				$flag++;
			}
		}
		$sql='INSERT INTO `'.$this->tab.'` ('.implode(',',$key).') VALUES '.implode(',',$val).';';
		$res=mysqli_query($this->con,$sql);
		return $res;
	}

    public function getRebate($arr,$agent){//获取返佣数据的父级
        foreach($arr as $k => $v){
            if($v['user_id']==$agent){
                if($v['position']==1){
                    return $this->getRebate($arr,$v['user_recommend']);
                }else{
                    return array('user_id'=>$v['user_id'],'group'=>$v['group'],'position'=>$v['position']);
                }
            }
        }
    }


}

function mt4_operation($request){
    $server = "103.14.78.198";
    $port = 1950;
    $socketPtr = fsockopen($server, $port, $errno, $errstr, 0.4);
    fputs($socketPtr, $request);
    $size = fgets($socketPtr, 64);
    $answer = "";
    $readed = 0;
    while($readed < $size){
        $part = fread($socketPtr, $size - $readed);
        $readed += strlen($part);
        $answer .= $part;
    }
    fclose($socketPtr);
    return $answer;
}

$min=58800;$max=58810;
$model=new db_connect('localhost','mansing','root','Mansing@SQL9340');




$y = date("Y");
$m = date("m");
$d = date("d");
$from = mktime(0, 0, 0, $m, $d, $y) - 20*(24 * 60 * 60)+1;
$to = mktime(0, 0, 0, $m, $d, $y);

//echo date('Y-m-d H:i:s',$from).'**************'.date('Y-m-d H:i:s',$to);die;
//返佣点击记录
$click_log['admin_id'] = 100;
$click_log['time'] = time();
$click_log['type'] = 1;
$click_res=$model->M('rebate_click_log')->add($click_log);//$click_res=1;
$filename=date('Ymd-His');
if($click_res){
    $has = $model->M('return_operation_log')->where(['time'=>$to,'type'=>1])->find();//查询当天是否有返佣
    if(empty($has)){
        $userAll=$model->M('user')->field('user_id,user_recommend,`group`,position')->where(['user_role'=>1])->select();
        $logins=[];//
        $allUser=[];
        foreach($userAll as $k => $v){
            $logins[]=$v['user_id'];
            $allUser[$v['user_id']]=$v;
        }
		$model->changeDB('mt4');
        $reoups=$model->M('mt4_trades')->field('LOGIN,sum(VOLUME)')
            ->where('(CMD between 0 and 1) and (LOGIN between '.$min.' and '.$max.') and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$from).'\' and \''.date('Y-m-d H:i:s',$to).'\') and (right(SYMBOL,2) = \'bo\')')
            ->group('LOGIN')->select();
        foreach ($reoups as $k => $v){
            if(!in_array($v['LOGIN'],$logins)){
                unset($reoups[$k]);
            }
        }
		$model->changeDB('mansing');
        $reoups=array_merge($reoups);
        if(empty($reoups)){
            $data=array('msg'=>'未找到交易记录','status'=>0);
            $filename.='-no trades.txt';
        }else{
            $group=$model->M('mt4_groups')->field('mt4_group,ratio')->select();
            $ratio=[];//每个组别的佣金比率
            foreach ($group as $k => $v){
                $ratio[$v['mt4_group']]=$v['ratio'];
            }
			
            $parent=[];//可以得到佣金的账户
            $rebateData=[];//最终需要返佣的数据
            foreach ($reoups as $k => $v){//获取自己的佣金返给谁
                if(!empty($allUser[$v['LOGIN']]) && ($allUser[$v['LOGIN']]['user_recommend']!=0)){
                    $v['ratio']=$ratio[$allUser[$v['LOGIN']]['group']];
                    $v['parent']=$model->getRebate($userAll,$allUser[$v['LOGIN']]['user_recommend']);
                    if(!empty($v['parent'])){//剔除没有父级的数据，防止无用循环
                        $v['money']=round($ratio[$v['parent']['group']]*round($v['sum(VOLUME)']/100),2);
                        if($v['money']!=0){$rebateData[]=$v;$parent[]=$v['parent']['user_id'];}//剔除金额为0的数据，防止无用循环
                    }
                }
                /*foreach ($userAll as $ke => $va){
                    if($v['login']==$va['user_id']){
                        $v['ratio']=$ratio[$va['group']];
                        $v['parent']=$this->getRebate($userAll,$va['user_recommend']);
                        if(!empty($v['parent'])){//剔除没有父级的数据，防止无用循环
                            $v['money']=round($ratio[$v['parent']['group']]*round($v['sum(volume)']/100),2);
                            if($v['money']!=0){$rebateData[]=$v;$parent[]=$v['parent']['user_id'];}//剔除金额为0的数据，防止无用循环
                        }
                        break;
                    }
                }*/
            }
			//print_r($parent);die;
            //print_r($rebateData);die;
            $parent=array_unique($parent);
            $parent=array_merge($parent);
            $finalData=[];
            foreach($parent as $k => $v){
                $money=0;
                foreach ($rebateData as $ke => $va){
                    if($v==$va['parent']['user_id']){
                        $money+=$va['money'];
                    }
                }
                $finalData[]=array('login'=>$v,'money'=>$money);
            }
            print_r($finalData);die;
            $rebate_data=[];
            foreach ($finalData as $k => $v){
                if($v['money']!=0){
                    $request = "action=changebalance&login=".$v['login']."&value=".$v['money']."&comment=CommBo".date("Ymd",strtotime("-1 day"))."\0";
                    $return = mt4_operation($request);
                    parse_str($return,$res);
                    $rebate_data[]=array(
                        'code'=>$res['result'],//状态码
                        'money'=>$v['money'],// 发放的佣金金额
                        'time'=>time(),//发放时间
                        'payee'=>$v['login'],//收款人
                        'from'=>$from,
                        'to'=>$to,
                        'type'=>1,
                        'order_num'=>$res['order']//订单号
                    );
                }
            }
            $res1=$model->M('rebate_log')->addAll($rebate_data);//将佣金发放信息存入数据库
            if($res1){//将操作记录写入数据库
                $return_operation_log['admin_id'] = 100;
                $return_operation_log['time'] = $to;
                $return_operation_log['type'] = 1;
                $res2 = M('return_operation_log')->add($return_operation_log);
                if ($res2) {
                    $data=array('msg'=>'操作成功','status'=>1);
                    $filename.='-success.txt';
                } else {
                    $filename.='-success-operation insert fail.txt';
                    $data=array('msg' => '佣金发放成功，操作记录未保存成功', 'status' => -1);
                }
            }else{
                $filename.='-success-insert fail.txt';
                $data=array('msg'=>'佣金发放成功，记录保存失败','status'=>-1);
            }
        }
    }else{
        $filename.='-success-Already issued.txt';
        $data=array('msg'=>'今日佣金已发放','status'=>0);
    }
}else{
    $filename.='-fail-retry.txt';
    $data=array('msg'=>'操作失败，请重试','status'=>0);
}
$data=var_export($data,true);
file_put_contents('C:/phpStudy/WWW/YuH/Uploads/rebateLog/'.$filename,$data);
?>